﻿using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using ERP.ERPSystem.HumanResources.Dto;
using ERP.ERPSystem.HumanResources;
using System.Collections.Generic;
using ERP.Migrations; 
using System.Linq;
using Volo.Abp.AspNetCore.Mvc;

namespace ERP.Web.Controllers.HumanResources
{
    public class JobGradeManagementController : AbpController
    {
        private readonly IJobGradeManagementServices _jobGradeManagementServices;

        public JobGradeManagementController(IJobGradeManagementServices jobGradeManagementServices)
        {
            _jobGradeManagementServices = jobGradeManagementServices;
        }

        /// <summary>
        /// 添加职级管理页面
        /// </summary>
        /// <returns></returns>
        public IActionResult AddJobGrade()
        {
            return View();
        }

        /// <summary>
        /// 添加职级管理
        /// </summary>
        /// <param name="jobGradeDto">职级信息DTO</param>
        /// <returns>返回操作结果</returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> AddJobGradeManage([FromBody] JobGradeDto jobGradeDto)
        {
            try
            {
                // 打印接收到的数据，用于调试
                Console.WriteLine($"Received data: {System.Text.Json.JsonSerializer.Serialize(jobGradeDto)}");

                if (jobGradeDto == null)
                {
                    return BadRequest(new { success = false, message = "提交的数据不能为空" });
                }

                // 验证必填字段
                if (string.IsNullOrWhiteSpace(jobGradeDto.JobGradeLevel))
                {
                    return BadRequest(new { success = false, message = "职级层次不能为空" });
                }
                if (string.IsNullOrWhiteSpace(jobGradeDto.JobGradeLevelName))
                {
                    return BadRequest(new { success = false, message = "职级层次名称不能为空" });
                }
                if (string.IsNullOrWhiteSpace(jobGradeDto.ReferenceColumn))
                {
                    return BadRequest(new { success = false, message = "备注不能为空" });
                }

                // 如果职级编码为空，则自动生成
                if (string.IsNullOrWhiteSpace(jobGradeDto.JobGradeCoding))
                {
                    jobGradeDto.JobGradeCoding = await GenerateJobGradeCoding();
                }

                // 验证薪资范围
                if (jobGradeDto.SalaryRangelower >= jobGradeDto.SalaryRangelimits)
                {
                    return BadRequest(new { success = false, message = "薪资范围上限必须大于下限" });
                }

                var result = await _jobGradeManagementServices.AddJobGrade(jobGradeDto);
                
                if (result > 0)
                {
                    return Ok(new { success = true, message = "添加成功" });
                }
                else
                {
                    return BadRequest(new { success = false, message = "添加失败" });
                }
            }
            catch (Exception ex)
            {
                // 记录异常信息
                Console.WriteLine($"Error in AddJobGradeManage: {ex}");
                return StatusCode(500, new { success = false, message = "服务器错误，请稍后重试" });
            }
        }

        /// <summary>
        /// 生成职级编码
        /// </summary>
        /// <returns>生成的职级编码</returns>
        [HttpPost]
        private async Task<string> GenerateJobGradeCoding()
        {
            var date = DateTime.Now.ToString("yyyyMMdd");
            var random = new Random();
            var randomNumber = random.Next(1000, 9999).ToString();
            return $"JG{date}{randomNumber}";
        }

        /// <summary>
        /// 显示职级管理页面
        /// </summary>
        /// <returns></returns>
        public IActionResult JobGradeQuery()
        {
            return View();
        }

        /// <summary>
        /// 显示职级管理
        /// </summary>
        /// <returns>职级列表</returns>
        [HttpGet]
        public async Task<IActionResult> GetJobGrades()
        {
            try
            {
                var result = await _jobGradeManagementServices.GetJobGrades();
                return Ok(result.ToList());
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { success = false, message = "获取数据失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 删除职级
        /// </summary>
        /// <param name="ids">要删除的职级ID列表</param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteJobGrade([FromBody] List<int> ids)
        {
            try
            {
                if (ids == null || !ids.Any())
                {
                    return BadRequest(new { success = false, message = "请选择要删除的职级" });
                }

                foreach (var id in ids)
                {
                    await _jobGradeManagementServices.DeleteJobGradee(id);
                }

                return Ok(new { success = true, message = "删除成功" });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { success = false, message = "删除失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 获取职级详情
        /// </summary>
        /// <param name="id">职级ID</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetJobGradeById(int id)
        {
            var jobGrade = await _jobGradeManagementServices.GetJobGradeByIdAsync(id);
            return Json(jobGrade);
        }

        /// <summary>
        /// 修改职级页面
        /// </summary>
        /// <param name="id">职级ID</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> EditJobGrade(int id)
        {
            return View();
        }

        /// <summary>
        /// 修改职级信息
        /// </summary>
        /// <param name="jobGradeDto">职级信息</param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> UpdateJobGrade([FromBody] JobGradeDto jobGradeDto)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return Json(new { success = false, message = "请检查输入数据的有效性" });
                }

                await _jobGradeManagementServices.UpdateJobGradeAsync(jobGradeDto);
                return Json(new { success = true, message = "修改成功" });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 批量删除职级
        /// </summary>
        /// <param name="ids">职级ID列表</param>
        /// <returns></returns>
        [HttpPost]
        [Route("BatchDeleteJobGrades")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> BatchDeleteJobGrades([FromBody] List<int> ids)
        {
            try
            {
                if (ids == null || !ids.Any())
                {
                    return BadRequest(new { success = false, message = "请选择要删除的职级" });
                }

                foreach (var id in ids)
                {
                    await _jobGradeManagementServices.DeleteJobGradee(id);
                }

                return Ok(new { success = true, message = "删除成功" });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { success = false, message = "删除失败：" + ex.Message });
            }
        }

        [HttpGet]
        public async Task<IActionResult> ExportJobGrades(
            string jobGradeCoding = null,
            string jobGradeLevel = null,
            string jobGradeLevelName = null,
            int? salaryRangelower = null,
            int? salaryRangelimits = null)
        {
            var fileBytes = await _jobGradeManagementServices.ExportJobGrades(
                jobGradeCoding,
                jobGradeLevel,
                jobGradeLevelName,
                salaryRangelower,
                salaryRangelimits);

            var fileName = $"职级管理_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
            return File(fileBytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);
        }
    }
}
